import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { message } from 'ant-design-vue'
import router from './router/index'

router.beforeEach((to, from, next) => {
  const loginUser = useLoginUserStore().loginUser
  const access :string[]= to.meta.access as  string[] ?? []
  //如果不存在access 或者noAuth，则不需要验证 直接放行
  if (access.includes('noAuth')||access.length === 0) {
    next()
  }
  //存在access，判断access的内容 如果admin则判断用户角色是否为admin
  if (access.includes('user') && !access.includes('admin')) {
    if (loginUser.id) {
      next()
    } else {
      next('/user/login')
      message.warning('请登录')
    }
  }
  if (access.includes('admin')) {
    if (loginUser.id && loginUser.userRole === 'admin') {
      next()
    } else {
      if (loginUser.id) {
        next('/user/login')
        message.warning('请登录')
      } else {
        message.warning('无权限')
        next('/noAuth')
      }
    }
  }
})
